package com.example.vueserver.vueserver.controller;

import com.alibaba.fastjson.JSON;
import com.example.vueserver.vueserver.bean.*;
import com.example.vueserver.vueserver.service.*;
import com.example.vueserver.vueserver.utils.SysMenusUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class LoginController {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysRoleService sysRoleService;
    @Autowired
    SysUserRoleService sysUserRoleService;
    @Autowired
    SysPermissionService sysPermissionService;
    @Autowired
    SysRoleMenuService sysRoleMenuService;
    @Autowired
    SysMenuService sysMenuService;


//    @CrossOrigin //vue中配置代理则这里就不需要配置跨域访问处理注解

    @RequestMapping("/api/login")
    public Map login(@RequestBody String loginInfo) {
        SysUser loginUser = JSON.parseObject(loginInfo,SysUser.class);
        String username = loginUser.getUsername();
        String password = loginUser.getPassword();
        System.out.println(username+"**********"+password);
        Map resultMap = new HashMap();
        SysUser user = sysUserService.selectByName(username);
        if (null != user) {
            if(password.equals(user.getPassword())){
                List<SysUserRole> sysUserRoleList = sysUserRoleService.listByUserId(user.getId());
                List<SysRole> roleList = new ArrayList<>();
                List<SysPermission> permissions = new ArrayList<>();
                List<SysMenu> menuList = new ArrayList<>();
                for (SysUserRole sur : sysUserRoleList) {
                    roleList.add(sysRoleService.selectById(sur.getRoleId()));
                }
                for (SysRole role : roleList) {
                    permissions.addAll(sysPermissionService.listByRoleId(role.getId()));
                    for(SysRoleMenu srm:sysRoleMenuService.listByRoleId(role.getId())){
                        menuList.add(sysMenuService.selectById(srm.getMenuId()));
                    }
                }
                resultMap.put("user", user);
                resultMap.put("roles", roleList);
                resultMap.put("permission", permissions);
                resultMap.put("menus", SysMenusUtils.getTreeMenu(menuList));
                resultMap.put("msg", "登陆成功");
                resultMap.put("msgCode",1);
            }else{
                resultMap.put("msgCode",0);
                resultMap.put("msg", "密码错误");
            }
        }else{
            resultMap.put("msgCode",0);
            resultMap.put("msg", "用户名不存在");
        }
        System.out.println(resultMap);
        return resultMap;
    }
}
